package com.zdp.chat.config;

import cn.hutool.extra.spring.SpringUtil;
import com.zdp.chat.service.WebSocketService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;


/**
 * 自定义处理（处理socket数据）
 */
@Slf4j
@ChannelHandler.Sharable
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private WebSocketService webSocketService;

    /**
     * 当web客户端连接后，触发该方法
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        this.webSocketService = SpringUtil.getBean(WebSocketService.class);
        log.info("channelId:{}正在连接服务器,环境初始化中请稍等...",ctx.channel().id());
    }


    /**
     * 断开后先触发闲置 -> 断开
     * 当web客户端断开连接后，触发该方法
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        webSocketService.removed(ctx.channel());
    }

    /**
     * 当web客户端闲置后，触发该方法
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        webSocketService.removed(ctx.channel());
    }

    /**
     * 心跳检查 服务端每隔n秒会检查客户端存活情况
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        this.webSocketService.authorize(ctx.channel());
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("异常发生，异常消息{}", cause.getMessage());
    }

    /**
     * 读取客户端发送的请求报文
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        log.info("接收到客户端msg:{}", textWebSocketFrame.text());
    }
}
